package com.yogee.topseller.activity;

import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.oned.rss.AbstractRSSReader;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.adapter.SubscriptionAdapter;
import com.yogee.topseller.bean.ProductInfoBean;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.bean.SubscribeBean;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.RefreshUtil;
import com.yogee.topseller.view.RefreshView;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 项目名称：TopSeller
 * 类描述：认购产品界面
 * 创建时间：2017/7/3 0003 13:46
 * 创建人：wangye
 * 修改备注：
 */
public class SubscriptionActivity extends HttpActivity implements RefreshUtil.OnRefreshListener, SubscriptionAdapter.OnYYItemClickListener {
    @BindView(R.id.subscription_already)
    TextView subscriptionAlready;
    @BindView(R.id.subscription_not)
    TextView subscriptionNot;
    @BindView(R.id.subscription_frame)
    FrameLayout subscriptionFrame;
    @BindView(R.id.img_already)
    ImageView img_already;
    @BindView(R.id.img_not)
    ImageView img_not;
    private View viewAlready;
    private View viewNot;
    private RecyclerView subscriptionAlreadyRecycler;
    private RecyclerView subscriptionNotRecycler;
    private TwinklingRefreshLayout alreadyRefresh;
    private TwinklingRefreshLayout notRefresh;
    private int types = -1;//刷新加载的时候判断当前页面是哪一个 1：已预约 0：未预约
    private SubscriptionAdapter adapter;
    private SubscriptionAdapter adapter1;
    List<SubscribeBean.ProListBean> listBeen = new ArrayList<>();
    private boolean isRefresh = true;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_subscription;
    }

    @Override
    protected void initView() {
//        e7130ea92e9f4f03abb86755702afd18    userId
        //初始状态
        initAlready();
        viewAlready = LayoutInflater.from(this).inflate(R.layout.view_subscription_already, null);
        viewNot = LayoutInflater.from(this).inflate(R.layout.view_subscription_not, null);
        subscriptionAlreadyRecycler = (RecyclerView) viewAlready.findViewById(R.id.subscription_already_recycler);
        subscriptionNotRecycler = (RecyclerView) viewNot.findViewById(R.id.subscription_not_recycler);

        alreadyRefresh = (TwinklingRefreshLayout) viewAlready.findViewById(R.id.subscription_already_refresh);
        alreadyRefresh.setHeaderView(new RefreshView(this));
        alreadyRefresh.setBottomView(new RefreshView(this));
        alreadyRefresh.setBottomHeight(50);
        notRefresh = (TwinklingRefreshLayout) viewNot.findViewById(R.id.subscription_not_refresh);
        notRefresh.setHeaderView(new RefreshView(this));
        notRefresh.setBottomView(new RefreshView(this));
        notRefresh.setBottomHeight(50);
        subscriptionFrame.addView(viewAlready);

        adapter1 = new SubscriptionAdapter(this);
        adapter1.setOnYYItemClickListener(this);
        subscriptionAlreadyRecycler.setLayoutManager(new LinearLayoutManager(this));
//        subscriptionAlreadyRecycler.addItemDecoration(new SpaceItemDecoration(10));
        subscriptionAlreadyRecycler.setAdapter(adapter1);
        alreadyRefresh.setOnRefreshListener(new RefreshUtil(this).refreshListenerAdapter());

        notRefresh.setOnRefreshListener(new RefreshUtil(this).refreshListenerAdapter());
    }

    private void initAlready() {
        types = 0;
        subscriptionAlready.setTextColor(getResources().getColor(R.color.colorStyle));
        subscriptionAlready.setBackgroundColor(0xfff5f5f5);
        subscriptionNot.setBackgroundColor(0xffe6e6e6);
        subscriptionNot.setTextColor(0xff4a4a4a);
        subscribe(AppUtil.getUserId(this), "0", "10", "0");
    }

    @OnClick({R.id.subscription_already, R.id.subscription_not, R.id.subscription_back_iv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.subscription_already://未预约
                types = 0;
                isRefresh = true;
                img_already.setVisibility(View.VISIBLE);
                img_not.setVisibility(View.INVISIBLE);
                subscriptionAlready.setTextColor(getResources().getColor(R.color.colorStyle));
                subscriptionAlready.setBackgroundColor(0xfff5f5f5);
                subscriptionNot.setBackgroundColor(0xffe6e6e6);
                subscriptionNot.setTextColor(0xff4a4a4a);
                subscriptionFrame.removeAllViews();
                subscriptionFrame.addView(viewAlready);
                subscriptionAlreadyRecycler.setAdapter(adapter1);
                subscribe(AppUtil.getUserId(this), "0", "10", "0");
                break;
            case R.id.subscription_not://已预约
                types = 1;
                isRefresh = true;
                img_not.setVisibility(View.VISIBLE);
                img_already.setVisibility(View.INVISIBLE);
                subscriptionAlready.setTextColor(0xff4a4a4a);
                subscriptionAlready.setBackgroundColor(0xffe6e6e6);
                subscriptionNot.setBackgroundColor(0xfff5f5f5);
                subscriptionNot.setTextColor(getResources().getColor(R.color.colorStyle));
                subscriptionFrame.removeAllViews();
                subscriptionFrame.addView(viewNot);
                adapter = new SubscriptionAdapter(this);
                subscriptionNotRecycler.setLayoutManager(new LinearLayoutManager(this));
//                subscriptionNotRecycler.addItemDecoration(new SpaceItemDecoration(10));
                subscriptionNotRecycler.setAdapter(adapter);
                subscribe(AppUtil.getUserId(this), "0", "10", "1");
                break;
            case R.id.subscription_back_iv:
                finish();
                break;
        }
    }
 
    @Override
    public void onRefresh() {
        isRefresh = true;
        if (1 == types) {
            subscribe(AppUtil.getUserId(this), "0", "10", "1");
        } else {
            subscribe(AppUtil.getUserId(this), "0", "10", "0");
        }
    }

    @Override
    public void onLoad() {
        isRefresh = false;
        if (1 == types) {
            subscribe(AppUtil.getUserId(this), listBeen.size() + "", "0", "1");
        } else {
            subscribe(AppUtil.getUserId(this), listBeen.size() + "", "0", "0");
        }
    }

    private void subscribe(String userId, String total, String count, final String type) {
        HttpManager.getInstance().subscribe(userId, total, count, type)
                .compose(bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<SubscribeBean>() {
            @Override
            public void onNext(SubscribeBean subscribeBean) {
                
                SubscriptionActivity.this.loadingFinished();
                if (isRefresh) {
                    listBeen.clear();
                    listBeen = subscribeBean.getProList();
                } else {
                    listBeen.addAll(subscribeBean.getProList());
                }
                if (0 == types) {
                    if (isRefresh) {
                        alreadyRefresh.finishRefreshing();
                    } else {
                        alreadyRefresh.finishLoadmore();
                    }
                    adapter1.setListBean(listBeen, 0);
                } else {
                    if (isRefresh) {
                        notRefresh.finishRefreshing();
                    } else {
                        notRefresh.finishLoadmore();
                    }
                    adapter.setListBean(listBeen, 1);
                }
            }
        }, this));
    }

    @Override
    public void onYJClick(String orderId) {
        speedyAppointment(orderId);
    }

    @Override
    public void onAutoClick(String orderId,int type) {
        setAutoTurnOrder(orderId,type);
    }

    private void speedyAppointment(String orderId) {
        HttpManager.getInstance().speedyAppointment(orderId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                subscribe(AppUtil.getUserId(SubscriptionActivity.this), "0", "10", "0");
            }
        }, this));
    }

    private void setAutoTurnOrder(String orderId,final int type) {
        HttpManager.getInstance().setAutoTurnOrder(orderId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if (type == 0){
                    ToastUtils.showToast(SubscriptionActivity.this,"自动转预约成功");
                }else{
                    ToastUtils.showToast(SubscriptionActivity.this,"已取消自动转预约成功");
                }
                subscribe(AppUtil.getUserId(SubscriptionActivity.this), "0", "10", "0");
            }
        }, this));
    }

    class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        int mSpace;

        /**
         * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
         * the number of pixels that the item view should be inset by, similar to padding or margin.
         * The default implementation sets the bounds of outRect to 0 and returns.
         * <p>
         * <p>
         * If this ItemDecoration does not affect the positioning of item views, it should set
         * all four fields of <code>outRect</code> (left, top, right, bottom) to zero
         * before returning.
         * <p>
         * <p>
         * If you need to access Adapter for additional data, you can call
         * {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
         * View.
         *
         * @param outRect Rect to receive the output.
         * @param view    The child view to decorate
         * @param parent  RecyclerView this ItemDecoration is decorating
         * @param state   The current state of RecyclerView.
         */
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.left = mSpace;
            outRect.right = mSpace;
            outRect.bottom = mSpace;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = mSpace;
            }

        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }
}